﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace Note_Smart_Last
{
    public partial class NoteBookListForm : Form
    {
        //打开笔记列表事件
        public event Action<NoteBook> OpenNoteList;
        //退出登录事件
        public event Action LogoutRequested;
        //存储所有笔记簿列表：
        private List<NoteBook> notebooks = new List<NoteBook>();

        //笔记簿目录存储路径
        private string notesRootDirectory;

        //颜色列表
        private List<Color> webColors = new List<Color>();

        //UI控件声明
        private FlowLayoutPanel noteBookPanel;
        private TextBox searchTextBox;
        private ToolStrip toolStrip;
        private ContextMenuStrip listContextMenu;

        //当前用户
        private string currentUser;

        //从登录界面之后直接来到这个界面
        public NoteBookListForm(string username)
        {
            currentUser = username;
            notesRootDirectory = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            "EnhancedNoteBooks",
            username); // 添加用户名目录层级
            SetupUI();
            LoadNoteBooks();
            SetupContextMenu();
            LoadWebColors();
            this.Text = $"笔记簿列表-当前用户：{username}";
        }

        //获取所有Web颜色
        private void LoadWebColors()
        {
            // 获取所有Web标准颜色
            foreach (KnownColor knownColor in Enum.GetValues(typeof(KnownColor)))
            {
                Color color = Color.FromKnownColor(knownColor);
                if (color.IsSystemColor) continue; // 排除系统颜色

                // 添加Web标准颜色
                webColors.Add(color);
            }
        }

        //设置UI布局
        private void SetupUI()
        {
            this.Text = "笔记簿列表";
            this.Size = new Size(1000, 700);
            this.StartPosition = FormStartPosition.CenterScreen;

            var mainPanel = new Panel { Dock = DockStyle.Fill };

            // 搜索框
            var searchPanel = new Panel { Dock = DockStyle.Top, Height = 50 };
            searchTextBox = new TextBox { Dock = DockStyle.Fill, PlaceholderText = "输入关键词搜索笔记簿…" };
            searchTextBox.TextChanged += SearchTextBox_TextChanged;
            searchPanel.Controls.Add(searchTextBox);

            // 工具栏
            toolStrip = new ToolStrip { Dock = DockStyle.Top };
            toolStrip.Items.Add(new ToolStripButton("新建笔记簿", null, NewNoteButton_Click));
            toolStrip.Items.Add(new ToolStripButton("打开笔记簿", null, OpenNoteButton_Click));
            toolStrip.Items.Add(new ToolStripSeparator());
            toolStrip.Items.Add(new ToolStripButton("退出登录", null, LogoutButton_Click));

            // 笔记簿面板
            noteBookPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                AutoSize = false,
                WrapContents = true,
                FlowDirection = FlowDirection.LeftToRight,
                AutoScroll = true,
                Padding = new Padding(10),
                Margin = new Padding(10)
            };

            mainPanel.Controls.Add(noteBookPanel);
            mainPanel.Controls.Add(searchPanel);
            this.Controls.Add(mainPanel);
            this.Controls.Add(toolStrip);
        }

        //加载所有笔记簿
        private void LoadNoteBooks()
        {
            noteBookPanel.SuspendLayout();
            noteBookPanel.Controls.Clear();
            notebooks.Clear();

            if (!Directory.Exists(notesRootDirectory))
            {
                Directory.CreateDirectory(notesRootDirectory);
                noteBookPanel.ResumeLayout();
                return;
            }

            //遍历所有笔记簿目录
            foreach (var dir in Directory.GetDirectories(notesRootDirectory))
            {
                try
                {
                    var notebook = NoteBook.LoadFromDirectory(dir);
                    notebooks.Add(notebook);
                    AddNotebookCard(notebook);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"加载笔记簿失败：{ex.Message}");
                }
            }

            noteBookPanel.ResumeLayout();
        }

        //添加笔记簿卡片
        private void AddNotebookCard(NoteBook notebook)
        {
            // 读取封面配置
            var coverPath = Path.Combine(notebook.DirectoryPath, "cover.config");
            string coverSetting = File.Exists(coverPath) ? File.ReadAllText(coverPath) : "";

            // 创建书本控件
            var bookControl = new BookControl
            {
                Title = notebook.Name,
                PageCount = GetNoteCount(notebook.DirectoryPath),
                CreatedTime = notebook.CreatedTime,
                Tag = notebook
            };

            // 设置封面
            if (coverSetting.StartsWith("color:"))
            {
                string colorName = coverSetting.Substring(6);
                try
                {
                    bookControl.CoverColor = Color.FromName(colorName);
                }
                catch
                {
                    bookControl.CoverColor = Color.LightGray;
                }
            }
            else if (coverSetting.StartsWith("image:"))
            {
                string imagePath = coverSetting.Substring(6);
                try
                {
                    // 使用临时文件加载图片
                    string tempPath = Path.GetTempFileName();
                    File.Copy(imagePath, tempPath, true);
                    bookControl.CoverImage = Image.FromFile(tempPath);
                    File.Delete(tempPath);
                }
                catch
                {
                    bookControl.CoverColor = Color.LightGray;
                }
            }
            else
            {
                // 使用默认封面颜色
                bookControl.CoverColor = Color.FromArgb(240, 220, 180); // 米黄色书本
            }

            // 双击事件
            bookControl.DoubleClick += (sender, e) => {
                OpenNoteList?.Invoke(notebook);
            };

            // 右键事件
            bookControl.MouseRightClick += (sender, e) => {
                listContextMenu.Tag = notebook;

                // 选中当前书本
                foreach (Control control in noteBookPanel.Controls)
                {
                    if (control is BookControl book)
                    {
                        book.IsSelected = control == sender;
                    }
                }

                listContextMenu.Show(bookControl, e.Location);
            };


            //鼠标悬停效果
            bookControl.MouseEnter += (sender, e) => {
                var book = (BookControl)sender;
                if (book.CoverImage != null)
                {
                    // 在图片上绘制一层半透明白色图案
                    using (Graphics g = book.CreateGraphics())
                    {
                        using (Brush brush = new SolidBrush(Color.FromArgb(50, 255, 255, 255)))
                        {
                            g.FillRectangle(brush, new Rectangle(0, 0, book.Width, book.Height));
                        }
                    }
                }
                else
                {
                    // 调整纯色亮度
                    book.CoverColor = Color.FromArgb(
                        Math.Min(255, book.CoverColor.R + 25),
                        Math.Min(255, book.CoverColor.G + 25),
                        Math.Min(255, book.CoverColor.B + 25)
                    );
                }
            };


            //鼠标离开
            bookControl.MouseLeave += (sender, e) => {
                var book = (BookControl)sender;
                if (book.CoverImage != null)
                {
                    book.Invalidate(); // 刷新控件，移除半透明图案
                }
                else
                {
                    // 恢复原始纯色
                    // 重新读取封面配置以恢复原始颜色
                    coverSetting = File.Exists(coverPath) ? File.ReadAllText(coverPath) : "";
                    if (coverSetting.StartsWith("color:"))
                    {
                        string colorName = coverSetting.Substring(6);
                        try
                        {
                            book.CoverColor = Color.FromName(colorName);
                        }
                        catch
                        {
                            book.CoverColor = Color.LightGray;
                        }
                    }
                    else
                    {
                        book.CoverColor = Color.FromArgb(240, 220, 180);
                    }
                }
            };

            noteBookPanel.Controls.Add(bookControl);
        }

        private int GetNoteCount(string directory)
        {
            return Directory.GetFiles(directory, "*.rtf").Length;
        }

        //设置右键上下菜单
        private void SetupContextMenu()
        {
            listContextMenu = new ContextMenuStrip();

            var deleteItem = new ToolStripMenuItem("删除");
            var renameItem = new ToolStripMenuItem("重命名");
            var coverItem = new ToolStripMenuItem("封面");

            deleteItem.Click += DeleteNotes_Click;
            renameItem.Click += Rename_Click;
            coverItem.DropDownOpening += CoverMenu_DropDownOpening;

            listContextMenu.Items.Add(deleteItem);
            listContextMenu.Items.Add(renameItem);
            listContextMenu.Items.Add(new ToolStripSeparator());
            listContextMenu.Items.Add(coverItem);
        }

        //封面菜单打开事件
        private void CoverMenu_DropDownOpening(object sender, EventArgs e)
        {
            var coverItem = sender as ToolStripMenuItem;
            coverItem.DropDownItems.Clear();

            // 按色系分组（简化版）
            var colorGroups = new Dictionary<string, List<Color>>
    {
        { "红色系", new List<Color>() },
        { "绿色系", new List<Color>() },
        { "蓝色系", new List<Color>() },
        { "黄色系", new List<Color>() },
        { "紫色系", new List<Color>() },
        { "灰色系", new List<Color>() }
    };

            // 按色系分类颜色
            foreach (var color in webColors)
            {
                if (color.R > color.G && color.R > color.B)
                    colorGroups["红色系"].Add(color);
                else if (color.G > color.R && color.G > color.B)
                    colorGroups["绿色系"].Add(color);
                else if (color.B > color.R && color.B > color.G)
                    colorGroups["蓝色系"].Add(color);
                else if (color.R > 180 && color.G > 180)
                    colorGroups["黄色系"].Add(color);
                else if (color.R == color.G && color.R == color.B)
                    colorGroups["灰色系"].Add(color);
                else
                    colorGroups["紫色系"].Add(color);
            }

            // 添加分组菜单
            foreach (var group in colorGroups)
            {
                if (group.Value.Count == 0) continue;

                var groupItem = new ToolStripMenuItem(group.Key);
                foreach (var color in group.Value)
                {
                    var colorItem = new ToolStripMenuItem(color.Name);
                    colorItem.BackColor = color;
                    colorItem.ForeColor = GetContrastColor(color);
                    colorItem.Click += (s, args) => {
                        var notebook = listContextMenu.Tag as NoteBook;
                        SetNotebookCover(notebook, $"color:{color.Name}");
                    };
                    groupItem.DropDownItems.Add(colorItem);
                }
                coverItem.DropDownItems.Add(groupItem);
            }

            // 添加上传图片和清除封面选项
            coverItem.DropDownItems.Add(new ToolStripSeparator());
            coverItem.DropDownItems.Add(new ToolStripMenuItem("上传图片...", null, UploadCover_Click));
            coverItem.DropDownItems.Add(new ToolStripMenuItem("清除封面", null, (s, args) => {
                var notebook = listContextMenu.Tag as NoteBook;
                SetNotebookCover(notebook, "");
            }));
        }

        //上传封面图片
        private void UploadCover_Click(object sender, EventArgs e)
        {
            var notebook = listContextMenu.Tag as NoteBook;

            using (var openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp|所有文件|*.*";
                openFileDialog.Title = "选择封面图片";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        string newPath = Path.Combine(notebook.DirectoryPath, "cover.jpg");

                        // 如果目标文件已存在，先尝试删除它
                        if (File.Exists(newPath))
                        {
                            File.Delete(newPath);
                        }

                        // 复制新图片到笔记簿目录
                        File.Copy(openFileDialog.FileName, newPath);

                        // 设置封面
                        SetNotebookCover(notebook, $"image:{newPath}");
                        // 刷新书本控件的封面图片
                        var bookControl = noteBookPanel.Controls.Cast<BookControl>().FirstOrDefault(c => c.Tag == notebook);
                        if (bookControl != null)
                        {
                            try
                            {
                                // 使用临时文件加载图片
                                string tempPath = Path.GetTempFileName();
                                File.Copy(newPath, tempPath, true);
                                bookControl.CoverImage = Image.FromFile(tempPath);
                                File.Delete(tempPath);
                            }
                            catch
                            {
                                bookControl.CoverColor = Color.LightGray;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"更新封面失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        // 更新笔记簿封面显示
        private void UpdateNotebookCover(NoteBook notebook, string imagePath)
        {
            // 找到对应的BookControl
            foreach (var control in noteBookPanel.Controls)
            {
                if (control is BookControl bookControl && bookControl.Tag == notebook)
                {
                    // 使用创建副本的方式加载图片，避免文件锁定
                    using (var originalImage = Image.FromFile(imagePath))
                    {
                        // 创建图片副本
                        bookControl.CoverImage = new Bitmap(originalImage);
                    }

                    // 刷新控件
                    bookControl.Invalidate();
                    break;
                }
            }
        }


        //设置笔记簿封面
        private void SetNotebookCover(NoteBook notebook, string coverSetting)
        {
            var coverPath = Path.Combine(notebook.DirectoryPath, "cover.config");
            File.WriteAllText(coverPath, coverSetting);
            LoadNoteBooks(); // 刷新显示
        }

        //获取对比色(用于文字显示)
        private Color GetContrastColor(Color color)
        {
            int d = 0;
            int luminance = (int)((color.R * 0.299) + (color.G * 0.587) + (color.B * 0.114));

            if (luminance > 186)
                d = 0; // 亮背景用暗色文字
            else
                d = 255; // 暗背景用亮色文字

            return Color.FromArgb(d, d, d);
        }

        //搜索框文本变化处理
        private void SearchTextBox_TextChanged(object sender, EventArgs e)
        {
            string keyword = searchTextBox.Text.ToLower();

            foreach (Control control in noteBookPanel.Controls)
            {
                var notebook = control.Tag as NoteBook;
                bool match = notebook.Name.ToLower().Contains(keyword);

                // 匹配的笔记簿高亮显示
                if (match)
                {
                    control.BackColor = Color.LightYellow;
                    control.Visible = true;
                }
                else
                {
                    control.BackColor = control.BackgroundImage == null ? Color.LightGray : Color.Transparent;
                    control.Visible = string.IsNullOrEmpty(keyword);
                }
            }
        }

        //新建笔记簿
        private void NewNoteButton_Click(object sender, EventArgs e)
        {
            var newNotebook = new NoteBook(currentUser, $"新建笔记簿_{DateTime.Now:MMddHHmm}");
            newNotebook.CreateDirectory(notesRootDirectory);
            LoadNoteBooks(); // 刷新列表
        }

        //打开笔记簿
        private void OpenNoteButton_Click(object sender, EventArgs e)
        {
            if (listContextMenu.Tag != null)
            {
                var selectedNotebook = listContextMenu.Tag as NoteBook;
                OpenNoteList?.Invoke(selectedNotebook);
            }
            else
            {
                MessageBox.Show("请先选择一个笔记簿", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        // 打开笔记列表界面
        private void OpenNoteListForm(NoteBook notebook)
        {
            var noteListForm = new NotesListForm(notebook.DirectoryPath);
            noteListForm.FormClosed += (s, args) =>
            {
                this.Show();
                LoadNoteBooks(); // 刷新列表 
            };
            this.Hide();
            noteListForm.Show();
        }

        // 添加退出登录方法
        private void LogoutButton_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show("确定要退出登录吗？", "退出登录", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                LogoutRequested?.Invoke(); // 触发退出登录事件
            }
        }

        //打开编辑器
        private void OpenNoteEditor(Note note)
        {
            var editor = new NoteEditorForm(note);
            editor.FormClosed += (s, args) =>
            {
                this.Show();
                LoadNoteBooks();
            };
            this.Hide();
            editor.Show();
        }

        //删除笔记菜单点击事件
        private void DeleteNotes_Click(object sender, EventArgs e)
        {
            if (listContextMenu.Tag != null)
            {
                var notebook = listContextMenu.Tag as NoteBook;

                var result = MessageBox.Show($"确定要删除笔记簿 '{notebook.Name}' 吗?",
                    "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (result == DialogResult.Yes)
                {
                    notebook?.Delete();
                    LoadNoteBooks();
                }
            }
        }

        //右键重命名
        private void Rename_Click(object sender, EventArgs e)
        {
            if (listContextMenu.Tag == null) return;

            var notebook = listContextMenu.Tag as NoteBook;

            using (var inputDialog = new Form())
            {
                inputDialog.Text = "重命名笔记簿";
                inputDialog.Size = new Size(400, 150);
                inputDialog.StartPosition = FormStartPosition.CenterParent;

                var textBox = new TextBox
                {
                    Text = notebook.Name,
                    Dock = DockStyle.Top,
                    Margin = new Padding(20)
                };

                var btnConfirm = new Button
                {
                    Text = "确认",
                    DialogResult = DialogResult.OK,
                    Dock = DockStyle.Bottom
                };

                inputDialog.Controls.Add(textBox);
                inputDialog.Controls.Add(btnConfirm);
                inputDialog.AcceptButton = btnConfirm;

                if (inputDialog.ShowDialog() == DialogResult.OK)
                {
                    if (!string.IsNullOrWhiteSpace(textBox.Text))
                    {
                        notebook.Rename(textBox.Text.Trim());
                        SaveNotebookMeta(notebook);
                        LoadNoteBooks(); // 刷新显示
                    }
                }
            }
        }

        private void SaveNotebookMeta(NoteBook notebook)
        {
            var metaPath = Path.Combine(notebook.DirectoryPath, "notebook.meta");
            var metaData = new
            {
                DisplayName = notebook.Name,
                OriginalName = notebook.SecName,
                CreatedTime = notebook.CreatedTime
            };
            File.WriteAllText(metaPath, JsonConvert.SerializeObject(metaData));
        }
    }
}
